//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2005-2006
//
// Close element of polyline.
//

# include "StdAfx.h"
# include "ClosePolyline.h"
# include "AddPoint.h"
# include "Map.h"
# include "Selection.h"
# include "CombinedAction.h"

void ClosePolyline (rgn_t * _pRgn, size_t _cElement) {
	assert (_pRgn);
	assert (_pRgn->Kind == rkPolyline);
	assert (_cElement < _pRgn->elements.size ());

	points_t & points = _pRgn->elements [_cElement].points;
	const size_t cPoints = points.size ();
	if (cPoints <= 2)
		return;
	if (points [0] == points [cPoints - 1])
		return;

	AddPoint (_pRgn, _cElement, cPoints - 1, points [0]);
}

bool IsClosePolylineAppliable () {
	bool bAppliable = false;

	const size_t cSelItems = g_Selection.size ();
	for (size_t cSelItem = 0; cSelItem < cSelItems; ++ cSelItem) {
		find_info_t & SelItem = g_Selection [cSelItem];
		if (! SelItem.pLayer)
			continue;

		rgn_t & rgn = * SelItem.iRgn;			
		if (rgn.IsDeleted () || ! rgn.IsPolyline ())
			continue;

		const size_t cElements = rgn.elements.size ();
		for (size_t cElement = 0; cElement < cElements; ++ cElement) {
			rgn_element_t & element = rgn.elements [cElement];
			if (element.bDeleted)
				continue;

			if (
				SelItem.cElementOrOrigin == -1 ||
				SelItem.cElementOrOrigin == cElement
			) {
				points_t & points = element.points;
				const size_t cPoints = points.size ();
				if (cPoints <= 2)
					continue;
				if (points [0] == points [cPoints - 1])
					continue;

				bAppliable = true;
			}
		}
	}

	return bAppliable;
}

void CloseSelectedPolylines () {
	const size_t cDepth = BeginCombinedAction ();

	const size_t cSelItems = g_Selection.size ();
	for (size_t cSelItem = 0; cSelItem < cSelItems; ++ cSelItem) {
		find_info_t & SelItem = g_Selection [cSelItem];
		if (! SelItem.pLayer)
			continue;

		rgn_t & rgn = * SelItem.iRgn;			
		if (rgn.IsDeleted () || ! rgn.IsPolyline ())
			continue;

		const size_t cElements = rgn.elements.size ();
		for (size_t cElement = 0; cElement < cElements; ++ cElement) {
			rgn_element_t & element = rgn.elements [cElement];
			if (element.bDeleted)
				continue;

			if (
				SelItem.cElementOrOrigin == -1 ||
				SelItem.cElementOrOrigin == cElement
			) {
				points_t & points = element.points;
				const size_t cPoints = points.size ();
				if (cPoints <= 2)
					continue;
				if (points [0] == points [cPoints - 1])
					continue;

				AddPoint (& rgn, cElement, cPoints - 1, points [0]);
			}
		}
	}

	EndCombinedAction (cDepth, "close polyline(s)");
}